package handlers

import (
	"fmt"
	"strings"

	"go.uber.org/zap"
	"missevanbot/models"
	"missevanbot/modules"
	"missevanbot/modules/thirdparty"
	"missevanbot/utils"
)

// Chat returns a simple response.
func Chat(room *models.Room, user models.FmUser, text string) string {
	id := utils.Itoa(room.ID) + "-" + utils.Itoa(user.UserID)

	text = strings.TrimSpace(strings.ReplaceAll(text, fmt.Sprintf("@%s", room.BotName()), ""))
	resp, err := thirdparty.OwnThinkChat(id, text)
	if err != nil {
		zap.S().Error(room.Log("request own_think service failed", err))
		return chat(user.Username, "")
	}

	if resp.Message != "success" {
		zap.S().Warn(room.Log("own_think response not succeed", *resp))
		return chat(user.Username, "")
	}

	if resp.Data.Type != 5000 {
		zap.S().Warn(room.Log("own_think response type incorrect", *resp))
		return chat(user.Username, "")
	}

	return chat(user.Username, resp.Data.Info.Text)
}

func chat(name string, text string) string {
	if text == "" {
		text = modules.Word(modules.WordChat)
	}
	return fmt.Sprintf("@%s %s", name, text)
}
